import React, { useState, useEffect } from 'react'
import { Form, Select, message } from 'antd'
const FormItem = Form.Item

import {jsonp} from '@/common/utils'
import request from '@/common/utils/request'

import { FormWidgetProps } from '../FormWidgetRender/WidgetRender'
import { OptionsFetch } from '../index'
interface optionType {
  label: string;
  value: string | number | any;
  key?: string | number
  id?: string | number
}
interface FetchParam {
  action?: string;
  method?: string;
  parse?: string
}

function index({ newSchema, formInstance }: FormWidgetProps) {
  const { fieldName, options, ui, props } = newSchema
  // console.log('schema',schema,rest)
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { colSpan = 12, offset = 0, ...formItemReset } = ui
  const attribute: any = { allowClear: true, size: 'middle', placeholder: '请选择', placement: 'bottomLeft', labelInValue: true, ...props }
  const [optionsArr, setOptionsArr] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const params = Object.prototype.toString.call(options) === '[object Object]' && Object.prototype.toString.call((options as OptionsFetch)?.params) === '[object Object]' && Object.keys((options as OptionsFetch)?.params)?.length ? (options as OptionsFetch).params : null

  const fetchData = (params:any) => {
    if (params?.jsonp){
      return jsonp({
        url: params?.action as string,
        data: params?.params
      } as any)
    }
    return request({
      url: params?.action.includes('http') || params?.action.includes('/api') || params?.action.includes('/mock') ? `${params?.action}` : `${process.env.APP_BASE_API}${params?.action}`,
      method: params?.method,
      model: null,
      params: params?.params ? { ...params.params } : {}
    } as any)
  }
  // 字符串函数解析方法funcStrParse,参数是一段函数字符串，返回值是一个函数
  function funcStrParse(funcStr:string) {
    return Function('\'use strict\';return (' + funcStr + ')')()
  }
  function forMartArr (d:any[]){
    const arr:optionType[] = []
    d.forEach((item:any) => {
      arr.push({value: item[1], label: item[0]})
    })
    return arr
  }

  // 执行获取数据
  const executeFetchData = (fetchParam:FetchParam | any) => {
    if (Object.prototype.toString.call(fetchParam) === '[object Object]') {
      if (fetchParam?.action && fetchParam?.method) {
        setLoading(true)
        fetchData(fetchParam as any).then((res: any) => {
          const formatResult: Function = fetchParam?.parse ? funcStrParse(fetchParam?.parse) : null
          const data = formatResult ? formatResult(res) : res
          const result: optionType[] = formatResult ? data.some((d: any) => Object.prototype.toString.call(d) === '[object Array]') ? forMartArr(data) : data : res?.data
          setOptionsArr(result)
        }).finally(() => {
          setLoading(false)
        })
      } else {
        message.warning('请求接口的类型未设置或者接口地址有误！')
      }
    }
  }

  const setOptionsFn = () => {
    if (Object.prototype.toString.call(options) === '[object Array]') {
      // options为数组场景代表直接给予静态数据
      setOptionsArr(options as any[])
    }
  }

  const init = () => {
    // 初始化todo
    setOptionsFn()
  }

  useEffect(() => {
    if (Object.prototype.toString.call(params) === '[object Object]' || newSchema?.updateByWatch?.name) {
      const tmpParams = { ...JSON.parse(JSON.stringify(params)) }
      if (newSchema?.updateByWatch?.name) {
      // 依赖字段变化场景下清空当前字段值
        formInstance.setFieldsValue({ ...formInstance.getFieldsValue(), [newSchema.fieldName]: null })
        // 对params原有的字段判断在表单中是否存在，存在则取该字段值
        Object.keys(params).length && Object.keys(params).forEach((k: string) => {
          if (formInstance.getFieldValue(k) !== undefined) {
            tmpParams[k] = formInstance.getFieldValue(k)
          }
        })
        // options类型依赖场景则把依赖字段的值赋上
        if (newSchema.updateByWatch.type === 'options') {
          tmpParams[newSchema.updateByWatch.name] = newSchema.updateByWatch.value
        }
      }
      console.log('newSchema?.updateByWatch', newSchema?.updateByWatch)
      debugger
      executeFetchData({ ...options, params: {...tmpParams} })
    }
  }, [params, newSchema?.updateByWatch?.name, newSchema?.updateByWatch?.type])

  useEffect(() => {
    init()
  }, [])

  return (
    <FormItem
      {...formItemReset}
      name={fieldName}
    >
      <Select {...attribute} loading={loading} options={optionsArr}/>
    </FormItem>
    )
}
export default index
